package com.spark.actions;

import java.util.List;
import java.util.Map;


import org.apache.ibatis.session.SqlSession;

import com.spark.core.SparkContext;
import com.spark.dao.SessionFactory;

public class SelectAction {
	public static final String ACTIONS_SELECT_OBJECT = "selectObject";
	public static final String ACTIONS_SELECT_MAP = "selectMap";
	public static final String ACTIONS_SELECT_LIST = "selectList";
	
	public static final String SELECT_ID = "id";
	public static final String SELECT_RESULT = "result";
	public static final String SELECT_PARAMETER= "parameter";

	@SuppressWarnings("unchecked")
	public void selectList(SparkContext context, String nameSpace, String id, String result, String parameter) {
		Map<String, Object> model = context.getModel();
		SqlSession sqlSession = SessionFactory.getSession();
		try {
			List list = (List) sqlSession.selectList(nameSpace + "." + id,getParameter(context,parameter));
			model.put(result, list);
		} finally {
			SessionFactory.closeSession(sqlSession);
		}
	}
	
	@SuppressWarnings("unchecked")
	public void selectMap(SparkContext context, String nameSpace, String id, String result, String parameter) {
		Map<String, Object> model = context.getModel();
		SqlSession sqlSession = SessionFactory.getSession();
		try {
			Map map = (Map) sqlSession.selectOne(nameSpace + "." + id,getParameter(context,parameter));
			model.put(result, map);
		} finally {
			SessionFactory.closeSession(sqlSession);
		}
	}
	
	@SuppressWarnings("unchecked")
	public void selectObject(SparkContext context, String nameSpace, String id, String result, String parameter) {
		Map<String, Object> model = context.getModel();
		SqlSession sqlSession = SessionFactory.getSession();
		try {
			Object obj = (Object) sqlSession.selectOne(nameSpace + "." + id,getParameter(context,parameter));
			model.put(result, obj);
		} finally {
			SessionFactory.closeSession(sqlSession);
		}
	}
	
	@SuppressWarnings("unchecked")
	private Map getParameter(SparkContext context, String pstr) {
		Map map = context.getModel();		
		map.putAll(context.getSession());
		map.putAll(context.getParameter());
		if(pstr!=null){
			String[] args = pstr.split("&");
			for(int i=0;i<args.length;i++){
				String st = args[i];
				if(st!=null && st.indexOf("=")!=-1){
					String[] ps = st.split("=");
					map.put(ps[0], ps[1]);
				}
			}
		}
		return map;
	}
}
